#!/usr/bin/env python3
# _*_ coding: utf-8 _*_

import os
import re
import argparse


if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument(
        '-s', "--summary", default=False, action="store_true", help='小结')
    parser.add_argument(
        '-o', '--overview', default=False, action="store_true", help='本节概要')
    args = parser.parse_args()
    action = 'summary' if args.summary else 'overview'
    subtitle = '小结' if args.summary else '讲课内容概要'
    materials = {'summary': '小结', 'overview': '本节概要'}
    files = sorted([file for file in os.listdir('.')
                    if re.match(r'^[0-9][0-9]\.tex', file)])
    tex = '''\\documentclass[article]{mathart}\\geometry{a5paper,margin=1.5cm}
        \\setlist[enumerate,1]{
            listparindent=0em,
            label=\\textup{\\bfseries\\arabic*.},
            labelindent=0em,
            itemindent=\\parindent,
            widest,
            align=parleft,
            leftmargin=0em,
            labelsep=*,
        }
        \\setlist[enumerate,2]{
            listparindent=\\parindent,
            label=\\textup{(\\arabic*)},
            labelindent=0em,
            itemindent=0em,
            widest,
            align=parleft,
            leftmargin=\\parindent,
            labelsep=*,
        }
        \\author{sc@hsu.edu.cn}\\def\\pause{}\n\\begin{document}'''
    with open('main.tex') as f:
        content = f.read()
    chapter_title_m = re.search(r'\\renewcommand{\\mytitle}{(.*?)}', content)
    if chapter_title_m:
        tex = '\n'.join([tex, f'\\title{{{chapter_title_m.group(1)}\\\\ \\normalfont\\normalsize {subtitle}}}\\maketitle'])
    for file in files:
        with open(file) as f:
            content = f.read()
        section_title_m = re.search(r'\\section{.*$', content, re.M | re.A)
        section_title = section_title_m.group(0) if section_title_m else ''
        tex = '\n'.join([tex, section_title])
        for m in re.finditer(fr'\\begin{{frame}}{{{materials[action]}}}(.*?)\\end{{frame}}', content, re.S):
            tex = '\n'.join([tex, m.group(1)])
    concat_enumerate = re.compile(r'\\end{enumerate}\s*\\begin{enumerate}\s*\\setcounter{enumi}{[0-9]*}')
    tex = concat_enumerate.sub('', '\n'.join([tex, '\\end{document}']))
    with open(f'{action}.tex', 'w') as f:
        f.write(tex)
